package com.chaosj.webmagic.process;

import com.chaosj.webmagic.IConvertPage;
import com.chaosj.webmagic.dto.SearchRequestDto;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.ServiceLoader;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @className: GuShiWenProcess
 * @description:
 * @author: caoyangjie
 * @date: 2021/8/11
 **/
public class SearchProcess implements PageProcessor {

    private SearchRequestDto gswRDto;
    private static AtomicBoolean lock = new AtomicBoolean(false);

    public SearchProcess(SearchRequestDto gswRDto) {
        this.gswRDto = gswRDto;
        lock.set(false);
    }

    @Override
    public void process(Page page) {
        ServiceLoader.load(IConvertPage.class).forEach(cvt->{
            if( cvt.support(gswRDto.getEnums()) ){
                if( !lock.get() ){
                    cvt.init();
                    lock.compareAndSet(false, true);
                }
                cvt.convert(page);
            }
        });
    }

    @Override
    public Site getSite() {
        return Site.me().setDomain(gswRDto.getEnums().getDomain());
    }
}
